<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Java API | ElasticSearch 7.7 权威指南中文版</title>
	<meta name="keywords" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <meta name="description" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
	<link rel="stylesheet" type="text/css" href="../static/styles.css" />
	<script>
	var _link = 'api-java.html';
    </script>
</head>
<body>
<div class="main-container">
    <section id="content">
        <div class="content-wrapper">
            <section id="guide" lang="zh_cn">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                            <div style="color:gray; word-break: break-all; font-size:12px;">原英文版地址: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.7/api-java.html" rel="nofollow" target="_blank">https://www.elastic.co/guide/en/elasticsearch/reference/7.7/api-java.html</a>, 原文档版权归 www.elastic.co 所有<br/>本地英文版地址: <a href="../en/api-java.html" rel="nofollow" target="_blank">../en/api-java.html</a></div>
                        <!-- start body -->
                  <div class="page_header">
<strong>重要</strong>: 此版本不会发布额外的bug修复或文档更新。最新信息请参考 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html" rel="nofollow">当前版本文档</a>。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="xpack-alerting.html">Alerting on cluster and index events</a></span>
»
<span class="breadcrumb-node">Java API</span>
</div>
<div class="navheader">
<span class="prev">
<a href="transform-chain.html">« Chain payload transform</a>
</span>
<span class="next">
<a href="managing-watches.html">Managing watches »</a>
</span>
</div>
<div class="chapter">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="api-java"></a>Java API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java.asciidoc">edit</a>
</h2>
</div></div></div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<h3>Deprecated in 7.0.0.</h3>
<p>The <code class="literal">TransportClient</code> is deprecated in favour of the <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.7/java-rest-high.html" class="ulink" target="_top">Java High Level REST Client</a> and will be removed in Elasticsearch 8.0. The <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.7/java-rest-high-level-migration.html" class="ulink" target="_top">migration guide</a> describes all the steps needed to migrate.</p>
</div>
</div>
<p>X-Pack provides a Java client called <code class="literal">WatcherClient</code> that adds native Java
support for the Watcher.</p>
<p>To obtain a <code class="literal">WatcherClient</code> instance, make sure you first set up the
<code class="literal">XPackClient</code>.</p>
<h3>
<a id="_installing_xpackclient"></a>Installing XPackClient<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java.asciidoc">edit</a>
</h3>
<p>You first need to make sure the <code class="literal">x-pack-transport-7.7.1</code> JAR file is in the classpath.
You can extract this jar from the downloaded X-Pack bundle.</p>
<p>If you use Maven to manage dependencies, add the following to the <code class="literal">pom.xml</code>:</p>
<div class="pre_wrapper lang-xml">
<pre class="programlisting prettyprint lang-xml">&lt;project ...&gt;

   &lt;repositories&gt;
      &lt;!-- add the elasticsearch repo --&gt;
      &lt;repository&gt;
         &lt;id&gt;elasticsearch-releases&lt;/id&gt;
         &lt;url&gt;https://artifacts.elastic.co/maven&lt;/url&gt;
         &lt;releases&gt;
            &lt;enabled&gt;true&lt;/enabled&gt;
         &lt;/releases&gt;
         &lt;snapshots&gt;
            &lt;enabled&gt;false&lt;/enabled&gt;
         &lt;/snapshots&gt;
      &lt;/repository&gt;
      ...
   &lt;/repositories&gt;
   ...

   &lt;dependencies&gt;
      &lt;!-- add the x-pack jar as a dependency --&gt;
      &lt;dependency&gt;
         &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;
         &lt;artifactId&gt;x-pack-transport&lt;/artifactId&gt;
         &lt;version&gt;7.7.1&lt;/version&gt;
      &lt;/dependency&gt;
      ...
   &lt;/dependencies&gt;
   ...

 &lt;/project&gt;</pre>
</div>
<p>If you use Gradle, add the dependencies to <code class="literal">build.gradle</code>:</p>
<div class="pre_wrapper lang-groovy">
<pre class="programlisting prettyprint lang-groovy">repositories {
  /* ... Any other repositories ... */

  // Add the Elasticsearch Maven Repository
  maven {
    name "elastic"
    url "https://artifacts.elastic.co/maven"
  }
}

dependencies {
  // Provide the x-pack jar on the classpath for compilation and at runtime
  compile "org.elasticsearch.client:x-pack-transport:7.7.1"

  /* ... */
}</pre>
</div>
<p>You can also download the <a href="https://artifacts.elastic.co/maven/org/elasticsearch/client/x-pack-transport/7.7.1/x-pack-transport-7.7.1.jar" class="ulink" target="_top">X-Pack Transport JAR</a>
manually, directly from our Maven repository.</p>
<h3>
<a id="_obtaining_the_watcherclient"></a>Obtaining the <code class="literal">WatcherClient</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java.asciidoc">edit</a>
</h3>
<p>To obtain an instance of the <code class="literal">WatcherClient</code> you first need to create the
<code class="literal">XPackClient</code>. The <code class="literal">XPackClient</code> is a wrapper around the standard Java
Elasticsearch <code class="literal">Client</code>:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
import org.elasticsearch.xpack.core.XPackClient;
import org.elasticsearch.xpack.core.XPackPlugin;
import org.elasticsearch.core.watcher.client.WatcherClient;
...

TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
    .put("cluster.name", "myClusterName")
    ...
    .build())
    .addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));

XPackClient xpackClient = new XPackClient(client);
WatcherClient watcherClient = xpackClient.watcher();</pre>
</div>
<h3>
<a id="api-java-put-watch"></a>Put watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/put-watch.asciidoc">edit</a>
</h3>
<p>The put watch API either registers a new watch in Watcher or update an
existing one. Once registered, a new document will be added to the <code class="literal">.watches</code>
index, representing the watch, and the watch trigger will immediately be
registered with the relevant trigger engine (typically the scheduler, for the
<code class="literal">schedule</code> trigger).</p>
<div class="important admon">
<div class="icon"></div>
<div class="admon_content">
<p>Putting a watch must be done via this API only. Do not put a watch
            directly to the <code class="literal">.watches</code> index using Elasticsearch’s Index API.
            When the Elasticsearch security features are enabled, make sure no <code class="literal">write</code>
            privileges are granted to anyone over the <code class="literal">.watches</code> index.</p>
</div>
</div>
<p>The following example adds a watch with the <code class="literal">my-watch</code> id that has the following
characteristics:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
The watch schedule triggers every minute.
</li>
<li class="listitem">
The watch search input looks for any 404 HTTP responses that occurred in the
last five minutes.
</li>
<li class="listitem">
The watch condition checks if any hits where found.
</li>
<li class="listitem">
When hits are found, the watch action sends an email to the administrator.
</li>
</ul>
</div>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatchSourceBuilder watchSourceBuilder = WatchSourceBuilders.watchBuilder();

// Set the trigger
watchSourceBuilder.trigger(TriggerBuilders.schedule(Schedules.cron("0 0/1 * * * ?")));

// Create the search request to use for the input
SearchRequest request = Requests.searchRequest("idx").source(searchSource()
        .query(boolQuery()
                .must(matchQuery("response", 404))
                .filter(rangeQuery("date").gt("{{ctx.trigger.scheduled_time}}"))
                .filter(rangeQuery("date").lt("{{ctx.execution_time}}"))
        ));

// Create the search input
SearchInput input = new SearchInput(new WatcherSearchTemplateRequest(new String[]{"idx"}, null, SearchType.DEFAULT,
    WatcherSearchTemplateRequest.DEFAULT_INDICES_OPTIONS, new BytesArray(request.source().toString())), null, null, null);

// Set the input
watchSourceBuilder.input(input);

// Set the condition
watchSourceBuilder.condition(new ScriptCondition(new Script("ctx.payload.hits.total.value &gt; 1")));

// Create the email template to use for the action
EmailTemplate.Builder emailBuilder = EmailTemplate.builder();
emailBuilder.to("someone@domain.host.com");
emailBuilder.subject("404 recently encountered");
EmailAction.Builder emailActionBuilder = EmailAction.builder(emailBuilder.build());

// Add the action
watchSourceBuilder.addAction("email_someone", emailActionBuilder);

PutWatchResponse putWatchResponse = watcherClient.preparePutWatch("my-watch")
    .setSource(watchSourceBuilder)
    .get();</pre>
</div>
<p>While the above snippet flashes out all the concrete classes that make our watch,
using the available builder classes along with static imports can significantly
simplify and compact your code:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">PutWatchResponse putWatchResponse2 = watcherClient.preparePutWatch("my-watch")
        .setSource(watchBuilder()
                .trigger(schedule(cron("0 0/1 * * * ?")))
                .input(searchInput(new WatcherSearchTemplateRequest(new String[]{"idx"}, null, SearchType.DEFAULT,
                        WatcherSearchTemplateRequest.DEFAULT_INDICES_OPTIONS, searchSource()
                        .query(boolQuery()
                                .must(matchQuery("response", 404))
                                .filter(rangeQuery("date").gt("{{ctx.trigger.scheduled_time}}"))
                                .filter(rangeQuery("date").lt("{{ctx.execution_time}}"))
                        ).buildAsBytes())))
                .condition(compareCondition("ctx.payload.hits.total.value", CompareCondition.Op.GT, 1L))
                .addAction("email_someone", emailAction(EmailTemplate.builder()
                        .to("someone@domain.host.com")
                        .subject("404 recently encountered"))))
        .get();</pre>
</div>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
Use <code class="literal">TriggerBuilders</code> and <code class="literal">Schedules</code> classes to define the trigger
</li>
<li class="listitem">
Use <code class="literal">InputBuilders</code> class to define the input
</li>
<li class="listitem">
Use <code class="literal">ConditionBuilders</code> class to define the condition
</li>
<li class="listitem">
Use <code class="literal">ActionBuilders</code> to define the actions
</li>
</ul>
</div>
<h3>
<a id="api-java-get-watch"></a>Get watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/get-watch.asciidoc">edit</a>
</h3>
<p>This API retrieves a watch by its id.</p>
<p>The following example gets a watch with <code class="literal">my-watch</code> id:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("my-watch").get();</pre>
</div>
<p>You can access the watch definition by accessing the source of the response:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">XContentSource source = getWatchResponse.getSource();</pre>
</div>
<p>The <code class="literal">XContentSource</code> provides you methods to explore the source:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">Map&lt;String, Object&gt; map = source.getAsMap();</pre>
</div>
<p>Or get a specific value associated with a known key:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">String host = source.getValue("input.http.request.host");</pre>
</div>
<h3>
<a id="api-java-delete-watch"></a>Delete watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/delete-watch.asciidoc">edit</a>
</h3>
<p>The delete watch API removes a watch (identified by its <code class="literal">id</code>) from Watcher.
Once removed, the document representing the watch in the <code class="literal">.watches</code> index is
gone and it will never be executed again.</p>
<p>Please note that deleting a watch <span class="strong strong"><strong>does not</strong></span> delete any watch execution records
related to this watch from the watch history.</p>
<div class="important admon">
<div class="icon"></div>
<div class="admon_content">
<p>Deleting a watch must be done via this API only. Do not delete the
            watch directly from the <code class="literal">.watches</code> index using Elasticsearch’s DELETE
            Document API. If the Elasticsearch security features are enabled, make sure
            no <code class="literal">write</code> privileges are granted to anyone over the <code class="literal">.watches</code> index.</p>
</div>
</div>
<p>The following example deletes a watch with the <code class="literal">my-watch</code> id:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">DeleteWatchResponse deleteWatchResponse = watcherClient.prepareDeleteWatch("my-watch").get();</pre>
</div>
<h3>
<a id="api-java-execute-watch"></a>Execute watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/execute-watch.asciidoc">edit</a>
</h3>
<p>This API enables on-demand execution of a watch stored in the <code class="literal">.watches</code> index.
It can be used to test a watch without executing all its actions or by ignoring
its condition. The response contains a <code class="literal">BytesReference</code> that represents the
record that would be written to the <code class="literal">.watcher-history</code> index.</p>
<p>The following example executes a watch with the name <code class="literal">my-watch</code></p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">ExecuteWatchResponse executeWatchResponse = watcherClient.prepareExecuteWatch("my-watch")

    // execute the actions, ignoring the watch condition
    .setIgnoreCondition(true)

    // A map containing alternative input to use instead of the output of
    // the watch's input
    .setAlternativeInput(new HashMap&lt;String, Object&gt;())

    // Trigger data to use (Note that "scheduled_time" is not provided to the
    // ctx.trigger by this execution method so you may want to include it here)
    .setTriggerData(new HashMap&lt;String, Object&gt;())

    // Simulating the "email_admin" action while ignoring its throttle state. Use
    // "_all" to set the action execution mode to all actions
    .setActionMode("_all", ActionExecutionMode.FORCE_SIMULATE)

    // If the execution of this watch should be written to the `.watcher-history`
    // index and reflected in the persisted Watch
    .setRecordExecution(false)

    // Indicates whether the watch should execute in debug mode. In debug mode the
    // returned watch record will hold the execution vars
    .setDebug(true)

    .get();</pre>
</div>
<p>Once the response is returned, you can explore it by getting execution record
source:</p>
<div class="tip admon">
<div class="icon"></div>
<div class="admon_content">
<p>The <code class="literal">XContentSource</code> class provides convenient methods to explore the
      source</p>
</div>
</div>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">XContentSource source = executeWatchResponse.getRecordSource();
String actionId = source.getValue("result.actions.0.id");</pre>
</div>
<h3>
<a id="api-java-ack-watch"></a>Ack watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/ack-watch.asciidoc">edit</a>
</h3>
<p><a class="xref" href="actions.html#actions-ack-throttle" title="Acknowledgement and throttling">Acknowledging</a> a watch enables you to manually throttle
execution of the watch actions. The action’s <em>acknowledgement state</em> is stored in
the <code class="literal">status.actions.&lt;id&gt;.ack.state</code> structure.</p>
<p>The current status of the watch and the state of its actions are returned as part
of the <a class="xref" href="api-java.html#api-java-get-watch" title="Get watch API">get watch API</a> response:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("my-watch").get();
State state = getWatchResponse.getStatus().actionStatus("my-action").ackStatus().state();</pre>
</div>
<p>The action state of a newly created watch is <code class="literal">awaits_successful_execution</code>. When
the watch runs and its condition is met, the state changes to <code class="literal">ackable</code>.
Acknowledging the action sets the state to <code class="literal">acked</code>.</p>
<p>When an action state is set to <code class="literal">acked</code>, further executions of that action are
throttled until its state is reset to <code class="literal">awaits_successful_execution</code>. This happens
when the watch condition is no longer met (the condition evaluates to <code class="literal">false</code>).</p>
<p>The following snippet shows how to acknowledge an action. You specify the IDs of
the watch and the action you want to acknowledge—​in this example <code class="literal">my-watch</code> and
<code class="literal">my-action</code>:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">AckWatchResponse ackResponse = watcherClient.prepareAckWatch("my-watch").setActionIds("my-action").get();</pre>
</div>
<p>As a response to this request, the status of the watch and the state of the
action are returned and can be obtained from <code class="literal">AckWatchResponse</code> object:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatchStatus status = ackResponse.getStatus();
ActionStatus actionStatus = status.actionStatus("my-action");
ActionStatus.AckStatus ackStatus = actionStatus.ackStatus();
ActionStatus.AckStatus.State ackState = ackStatus.state();</pre>
</div>
<p>You can acknowledge multiple actions:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">AckWatchResponse ackResponse = watcherClient.prepareAckWatch("my-watch")
  .setActionIds("action1", "action2")
  .get();</pre>
</div>
<p>To acknowledge all actions of a watch, specify only the watch ID:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">AckWatchResponse ackResponse = watcherClient.prepareAckWatch("my-watch").get();</pre>
</div>
<h3>
<a id="api-java-activate-watch"></a>Activate watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/activate-watch.asciidoc">edit</a>
</h3>
<p>A watch can be either <a class="xref" href="how-watcher-works.html#watch-active-state" title="Watch active state">active or inactive</a>. This API
enables you to activate a currently inactive watch.</p>
<p>The status of an inactive watch is returned with the watch definition
when you call the <a class="xref" href="api-java.html#api-java-get-watch" title="Get watch API">get watch API</a>:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("my-watch").get();
boolean active = getWatchResponse.getStatus().state().isActive();</pre>
</div>
<p>The following snippet shows how you can activate a watch:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">ActivateWatchResponse activateResponse = watcherClient.prepareActivateWatch("my-watch", true).get();
boolean active = activateResponse.getStatus().state().isActive();</pre>
</div>
<p>The new state of the watch is returned as part of its overall status.</p>
<h3>
<a id="api-java-deactivate-watch"></a>Deactivate watch API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/deactivate-watch.asciidoc">edit</a>
</h3>
<p>A watch can be either <a class="xref" href="how-watcher-works.html#watch-active-state" title="Watch active state">active or inactive</a>. This API
enables you to deactivate a currently active watch.</p>
<p>The status of an active watch is returned with the watch definition
when you call the <a class="xref" href="api-java.html#api-java-get-watch" title="Get watch API">get watch API</a>:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">GetWatchResponse getWatchResponse = watcherClient.prepareGetWatch("my-watch").get();
boolean active = getWatchResponse.getStatus().state().isActive();</pre>
</div>
<p>The following snippet shows how you can deactivate a watch:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">ActivateWatchResponse activateResponse = watcherClient.prepareActivateWatch("my-watch", false).get();
boolean active = activateResponse.getStatus().state().isActive();</pre>
</div>
<p>The new state of the watch is returned as part of its overall status.</p>
<h3>
<a id="api-java-stats"></a>Stats API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/stats.asciidoc">edit</a>
</h3>
<p>The <code class="literal">stats</code> API returns the current Watcher metrics. You can control what
metrics this API returns using the <code class="literal">metric</code> parameter.</p>
<p>The following example queries the <code class="literal">stats</code> API :</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatcherStatsResponse watcherStatsResponse = watcherClient.prepareWatcherStats().get();</pre>
</div>
<p>A successful call returns a response structure that can be accessed as shown:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatcherBuild build = watcherStatsResponse.getBuild();

// The current size of the watcher execution queue
long executionQueueSize = watcherStatsResponse.getThreadPoolQueueSize();

// The maximum size the watch execution queue has grown to
long executionQueueMaxSize = watcherStatsResponse.getThreadPoolQueueSize();

// The total number of watches registered in the system
long totalNumberOfWatches = watcherStatsResponse.getWatchesCount();

// {watcher} state (STARTING,STOPPED or STARTED)
WatcherState watcherState = watcherStatsResponse.getWatcherState();</pre>
</div>
<h3>
<a id="api-java-service"></a>Service API<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/x-pack/docs/en/watcher/java/service.asciidoc">edit</a>
</h3>
<p>The Watcher <code class="literal">service</code> API allows the control the lifecycle of the Watcher
service. The following example starts the watcher service:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatcherServiceResponse watcherServiceResponse = watcherClient.prepareWatchService().start().get();</pre>
</div>
<p>The following example stops the watcher service:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatcherServiceResponse watcherServiceResponse = watcherClient.prepareWatchService().stop().get();</pre>
</div>
<p>The following example restarts the watcher service:</p>
<div class="pre_wrapper lang-java">
<pre class="programlisting prettyprint lang-java">WatcherServiceResponse watcherServiceResponse = watcherClient.prepareWatchService().restart().get();</pre>
</div>
</div>
<div class="navfooter">
<span class="prev">
<a href="transform-chain.html">« Chain payload transform</a>
</span>
<span class="next">
<a href="managing-watches.html">Managing watches »</a>
</span>
</div>
</div>

                  <!-- end body -->
                        </div>
                        <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                        
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </section>
</div>
<script src="../static/cn.js"></script>
</body>
</html>